﻿using System;
using System.Collections.Generic;
using HtmlAgilityPack;

namespace PivotPhysicsPlotsGenerator.Utilities
{
    /// <summary>
    /// Helper extensions that one can add onto HtmlNode for
    /// various operations.
    /// </summary>
    static class HtmlExtensions
    {
        /// <summary>
        /// Finds all child-nodes starting from the base node that satisfy some test.
        /// This is sort-of like SelectNodes, but it isn't cursor operated, it is recursive operated.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<HtmlNode> ScanSubNodes(this HtmlNode baseNode, Func<HtmlNode, bool> testForReturn)
        {
            if (baseNode.HasChildNodes)
            {
                foreach (var item in baseNode.ChildNodes)
                {
                    if (testForReturn(item))
                    {
                        yield return item;
                    }
                    else
                    {
                        foreach (var subitem in item.ScanSubNodes(testForReturn))
                        {
                            yield return subitem;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Scan for a particular named node in the tree - use recusion instead of the
        /// usual SelectNodes method which is cursor like.
        /// </summary>
        /// <param name="nodename"></param>
        /// <param name="baseNode"></param>
        /// <returns></returns>
        public static IEnumerable<HtmlNode> ScanSubNodes(this HtmlNode baseNode, string nodename)
        {
            return baseNode.ScanSubNodes(n => n.Name == nodename);
        }
    }
}
